package br.com.pentagrama.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import br.com.pentagrama.dto.Parametros;
import br.com.pentagrama.dto.ResultadoPing;
import br.com.pentagrama.service.IPing;

public class PingHttp extends PingGenerico implements IPing {

	private Parametros parametros;
	
	private static PingHttp instance;
	
	public static PingHttp getInstance() {
		if(instance == null) {
			instance = new PingHttp();
		}
		return instance;
	}
	
	private PingHttp() {
		this.parametros = Parametros.getInstance();
	}
	
	public long ping(String urlLink) throws IOException {
		HttpURLConnection connection = null;
		long inicio = System.currentTimeMillis();
	    URL url = new URL(urlLink);
	    connection = (HttpURLConnection) url.openConnection();
	    connection.setDoInput(true);  
        connection.setDoOutput(true);  
	    connection.connect();
//	    byte[] bytesEscrita = TransferenciaUtil.getBytes();
//		connection.getOutputStream().write(bytesEscrita);
	    InputStream is = connection.getInputStream();
	    long fim = System.currentTimeMillis();
	    long delay = fim - inicio;
	    return delay;
	}
	
	public ResultadoPing doPing(String destino, int vezes) {
		ResultadoPing resultadoPing = new ResultadoPing();
		for (int i = 0; i < vezes; i++) {
			try {
				long latencia = ping(destino);
				resultadoPing.getResultados().add(latencia);
			} catch (IOException e) {
				e.printStackTrace();
				resultadoPing.falha();
			}
		}
		return resultadoPing;
	}
}
